import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';
import { Button, message } from 'antd';
import { WeaSwitch } from 'comsMobx';
import {
  WeaFormItem,
  WeaLocaleProvider,
  WeaMoreButton,
  WeaDialog,
  WeaSearchGroup,
  WeaRichText,
} from 'ecCom';
import { transfStr } from '../../../util';

const getLabel = WeaLocaleProvider.getLabel;
const MAILPAGENAME = 'TEMPLATEEDIT';

@inject('settingStore')
@observer
class Edit extends Component {
  constructor(props) {
    super(props);
    this.prefixCls = 'email-setting-template-edit';
  }

  getInstance = (ref) => {
    if (!this.editRichText) {
      this.editRichText = ref;
    }
  };

  handleStatusChange = (status) => {
    if (status === 'ready') {
      this.richInstanceReady = true;
      this.editRichText.focus('first');
    }
  };

  getForm = (form, fields) => {
    const { isFormInit } = form;
    let group = [];
    isFormInit &&
      fields &&
      fields.map((c) => {
        let items = [];
        c.items.map((field) => {
          items.push({
            com: (
              <WeaFormItem
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaFormItem@xsazp3@${MAILPAGENAME}${field.domkey[0]}`}
                label={`${field.label}`}
                labelCol={{ span: `${field.labelcol}` }}
                wrapperCol={{ span: `${field.fieldcol}` }}
                className={`${this.preCls}-formItem`}
                error={form.getError(field)}
                tipPosition="bottom"
              >
                <WeaSwitch
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_WeaSwitch@ev28nn@${MAILPAGENAME}${field.domkey[0]}`}
                  fieldConfig={field}
                  form={form}
                />
              </WeaFormItem>
            ),
          });
        });
        group.push(
          <WeaSearchGroup
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaSearchGroup@ieb94l@${MAILPAGENAME}form`}
            col={1}
            title={c.title}
            needTigger={true}
            showGroup={c.defaultshow}
            items={items}
          />,
        );
      });
    return group;
  };

  getFormContent = editRichValue => (
    <WeaSearchGroup
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaSearchGroup@4efm6o`}
      needTigger
      showGroup
      title={getLabel(28053, '模板内容')}
    >
      <div className={`${this.preCls}-formcontent`}>
        <WeaRichText
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaRichText@1m8bdu`}
          ref={this.getInstance}
          value={editRichValue}
          ckConfig={{
            toolbar: [
              { name: 'document', items: ['Source'] },
              {
                name: 'paragraph',
                items: [
                  'JustifyLeft',
                  'JustifyCenter',
                  'JustifyRight',
                  '-',
                  'NumberedList',
                  'BulletedList',
                ],
              },
              { name: 'styles', items: ['Format', 'Font', 'FontSize'] },
              { name: 'colors', items: ['TextColor'] },
              {
                name: 'basicstyles',
                items: ['Bold', 'Italic', 'Underline', 'Strike'],
              },
              { name: 'insert', items: ['Image', 'Table', 'Smiley'] },
            ],
            height: 260,
            uploadUrl: '/api/blog/fileupload/uploadimage',
          }}
          onStatusChange={this.handleStatusChange}
          onToolsChange={transfStr}
        />
      </div>
    </WeaSearchGroup>
  );

  /* 新建弹窗打开 */
  newTemplate = (params, callback) => {
    const {
      settingStore: { templateStore },
    } = this.props;
    const { getEmailTemplateCondition, setStoreState } = templateStore;
    getEmailTemplateCondition(params, () => {
      setStoreState({ editTitle: getLabel(28051, '新建模板') });
      if (callback && typeof callback === 'function') callback();
    });
  };

  onSubmit = () => {
    const {
      settingStore: { templateStore },
      onSubmit,
    } = this.props;
    const { markUserMailTemplate, editId, editType } = templateStore;
    if (
      this.richInstanceReady &&
      this.editRichText &&
      !this.editRichText.checkMode()
    ) {
      message.error(
        getLabel(
          '384536',
          '不能以源码模式或markdown模式保存，请将编辑器切换到可视化模式',
        ),
      );
      return;
    }
    let templateContent =
      (this.richInstanceReady &&
        this.editRichText &&
        this.editRichText.getData()) ||
      '';
    let params = { templateContent, operation: 'add' };
    params =
      editId === ''
        ? params
        : {
            ...params,
            operation: 'update',
            id: editId,
            templateType: editType,
          };
    markUserMailTemplate(params, (res) => {
      if (onSubmit && typeof onSubmit === 'function') onSubmit(res);
      this.onCancel();
    });
  };

  onCancel = () => {
    const {
      settingStore: { templateStore },
      onCancel,
    } = this.props;
    const { editForm, setStoreState } = templateStore;
    setStoreState({
      editRichValue: '',
      editTitle: '',
      editId: '',
      editType: '',
    });
    editForm.resetForm();
    this.editRichText = null;
    this.richInstanceReady = false;
    if (onCancel && typeof onCancel === 'function') onCancel();
  };

  onSave = () => {
    const {
      settingStore: { templateStore },
    } = this.props;
    templateStore.onEditSubmit(this.onSubmit);
  };

  render() {
    const {
      settingStore: { templateStore },
      visible,
    } = this.props;
    const { editTitle, editForm, editFields, editRichValue } = templateStore;
    const buttons = [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@f8cf8b@${MAILPAGENAME}save`}
        type="primary"
        onClick={this.onSave}
      >
        {getLabel(30986, '保存')}
      </Button>,
      <WeaMoreButton
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaMoreButton@58azwy@${MAILPAGENAME}more`}
      />,
    ];
    return (
      <WeaDialog
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_WeaDialog@6h38eh`}
        icon="icon-coms-email"
        iconBgcolor="#a0b0ba"
        title={editTitle}
        style={{ width: 787, height: 500 }}
        className={this.prefixCls}
        visible={visible}
        onCancel={this.onCancel}
        buttons={buttons}
        hasScroll
      >
        {this.getForm(editForm, editFields)}
        {this.getFormContent(editRichValue)}
      </WeaDialog>
    );
  }
}

/*
  外部调用方式：
  visible: must 控制弹窗显隐
  onCancel: 取消/关闭弹窗回调
  onSubmit: 保存回调
  open方法： 通过ref调用newTemplate(params, callback)
*/

export default Edit;
